<?php

class Europa_Route
{
	protected
		$_pattern,
		
		$_map,
		
		$_reverse,
		
		$_params = array(),
		
		$_hasMatch = false;
	
	
	
	public function __construct($pattern, $map = array(), $reverse = null)
	{
		$this->_pattern = $pattern;
		$this->_reverse = $reverse;
		$this->_map     = $map;
	}
	

	
	public function process($uri = null)
	{
		$uri = $uri ? $uri : Europa_Controller::getActiveInstance()->requestUri;
		
		preg_match_all('#' . $this->_pattern . '#', $uri, $matches);
		
		if ($matches) {
			$matches = $matches[1];
			
			foreach ($this->_map as $index => $name) {
				if (array_key_exists($index, $matches)) {
					$this->_params[$name] = $matches[$index];
				}
			}
			
			$this->_hasMatch = true;
		} else {
			$this->_hasMatch = false;
		}
		
		return $this;
	}
	
	public function reverseEngineer($params = array())
	{
		$parsed = $this->_reverse;
		
		foreach ($params as $name => $value) {
			$parsed = str_replace(':' . $name, $value, $parsed);
		}
		
		return $parsed;
	}
	
	public function hasMatch()
	{
		return $this->_hasMatch;
	}
	
	public function getController()
	{
		return $this->getParam('controller', 'index');
	}
	
	public function getAction()
	{
		return $this->getParam('action', 'index');
	}
	
	public function getParam($name, $defaultValue = null)
	{
		return array_key_exists($name, $this->_params)
			? $this->_params[$name]
			: $defaultValue;
	}
	
	public function getParams()
	{
		return $this->_params;
	}
}